using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Globalization;
using Mahjong.UI;
namespace Mahjong.UI
{
public class PlayerUI : MonoBehaviour,IPlayerUI
{ 
     // 新增必须的序列化字段
    [SerializeField] private GameObject handCardPrefab;  // 手牌预制体
    [SerializeField] private Transform handCardArea; // 手牌区
    [SerializeField] private GameObject discardCardPrefab; // 弃牌预制体
    [SerializeField] private Transform discardCardArea; // 弃牌区
    [SerializeField] private GameObject operationPanelPrefab; // 操作面板预制体
    [SerializeField] private GameObject gameEndPanelPrefab; // 游戏结束面板预制体
    [SerializeField] private GameObject conflictOptionsPanelPrefab; // 冲突选项面板预制体
    [SerializeField] private Canvas canvas; // UI画布
    private Dictionary<int, Player> playerObjects = new Dictionary<int, Player>();//存储玩家对象的字典
    private Dictionary<int, List<int>> playerHandCards = new Dictionary<int, List<int>>();//存储玩家手牌信息
    private Dictionary<int,GameObject> playerDiscardCardObjects=new Dictionary<int, GameObject>();//存储玩家弃牌对象字典
    private Dictionary<int, GameObject> playerHandCardObjects = new Dictionary<int, GameObject>();//存储玩家手牌对象字典
    private GameObject currentOperationPanel;//当前操作面板
    private CardUI currentSelectedCard;//当前选中的牌
    private float raiseCardDuration=1.0f;//等候操作响应时默认等待时间
    private float extendedRaiseCardDuration=5.0f;//延长后的等待时间
    private bool isCardRaised=false;//是否有牌被举起
    private Mahjong.UI.CardUI cardUI;//当前操作的牌
    private Action<int> cardClickedCallback; // 卡牌点击回调
    private enum RaiseState
    {
        NotRaised,
        IsRaised,
        IsRaisedAgain
    }
    private RaiseState currentRaiseState=RaiseState.NotRaised;//初始化为未举起状态
    private float raiseTimer=0.0f;//计时器
    private int currentRaisePlayerId = -1;//当前举起的玩家id

    
        //手牌区自动排序的逻辑
        public void LoadHandCardScene(int playerId, List<int> handCard)
        {
            ClearHandCard(playerId);
            //加载手牌区资源
            GameObject handCardScene = Resources.Load<GameObject>("C:/mahjong_layout/Assets/Resources/handCardScene");
            if (handCardScene != null)
            {
                Instantiate(handCardScene, transform);
            }
            else
            {
                Debug.LogError("Hand card scene not found!");
            }

            //实现手牌自动排序
            handCard.Sort();
            foreach (var card in handCard)
            {
                //加载手牌资源
                GameObject cardObj = Resources.Load<GameObject>("C:/mahjong_layout/Assets/Resources/pile.png");
                if (cardObj != null)
                {
                    GameObject instantiatedCard = Instantiate(cardObj, transform);
                    //通过Instantiate实例化出一个麻将牌对象，获取该卡牌对象上挂载的CardUI组件，调用初始化方法
                    instantiatedCard.GetComponent<CardUI>().initialize(card);
                }
                else
                {
                    Debug.LogError("Card prefab not found!");
                }
            }
        }
         //吃牌区的逻辑
        public void ShowChiToSelector(List<List<int>> options, Action<List<int>> callback)
        {
            //加载吃牌区资源
            GameObject chiCardScene = Resources.Load<GameObject>("C:/mahjong_layout/Assets/Resources/chiCardScene");
            if (chiCardScene != null)
            {
                Instantiate(chiCardScene, transform);
            }
            else
            {
                Debug.LogError("Chi card scene not found!");
            }

            //显示吃牌选项
            foreach (var option in options)
            {
                //创建选项按钮
                GameObject optionBtn = new GameObject("ChiOptionButton");
                optionBtn.transform.SetParent(transform);
                //设置按钮点击事件
                Button btnComponent = optionBtn.AddComponent<Button>();
                btnComponent.onClick.AddListener(() =>
                {
                    callback(option);
                });
            }
        }

    // 更新手牌界面，为按钮添加点击事件
    public void UpdateHandScene(int playerId, List<int> handCard)
{
    ClearHandCard(playerId);
    foreach (var card in handCard)
    {
        if (!playerHandCardObjects.ContainsKey(card))
        {
            // 实例化手牌对象
            GameObject cardObj = Instantiate(handCardPrefab, handCardArea);
            // 初始化卡牌
            cardObj.GetComponent<CardUI>().Initialize(card);
            // 为按钮添加点击事件
            Button button = cardObj.GetComponent<Button>();
            button.onClick.AddListener(() =>
            {
                // 触发点击事件
                OnCardClicked(card);
            });
            playerHandCardObjects[card] = cardObj;
        }
    }
}
    //返回手牌举起状态
    public bool IsCardRaised()
    {
        return currentRaiseState != RaiseState.NotRaised;
    }
    
    //更新手牌举起准备打出的界面，默认显示1秒后落下
    public void UpdateRaiseCardScene(int playerId, List<int> handCard,bool isRaised)
    {
        if(isRaised)//举起
      {     
        if(currentRaiseState!=RaiseState.NotRaised)//如果已经有举起的牌，先重置计时器和状态
        {
            raiseTimer=0.0f;
            currentRaiseState=RaiseState.IsRaisedAgain;//状态修改为再次举起
        }
        else
        {
            currentRaiseState=RaiseState.IsRaised;//状态为举起
        }
        currentRaisePlayerId = playerId;//记录当前举起的玩家id
        UpdateHandScene(playerId,handCard);//更新手牌,显示举起的牌
      }  
        //如果其他玩家有响应，则重置时间为5秒
    
        else//无需举起
      {
        UpdateHandScene(playerId,handCard);
        currentRaiseState=RaiseState.NotRaised;
        raiseTimer=0.0f;
        currentRaisePlayerId = -1;
      }
    }  


    //重置举起时间
    public void ResetRaiseCardTimer()
    {
        if(currentRaiseState==RaiseState.IsRaised)//如果已经有举起的牌，先重置计时器和状态
        {
            currentRaiseState=RaiseState.IsRaisedAgain;//状态修改为再次举起
            raiseTimer=0.0f;
        }
    }
    //更新举起状态和计时器
    private void Update()
    {
        if(currentRaiseState==RaiseState.IsRaised)
        {
            raiseTimer+=Time.deltaTime;
            if(raiseTimer>=raiseCardDuration)
            {
                //等待时间结束后，执行落下的动作
                currentRaiseState=RaiseState.NotRaised;//重置状态
                raiseTimer=0.0f;
                if(currentRaisePlayerId!=-1)
                {
                UpdateHandScene(currentRaisePlayerId,new List<int>());
                }
            }
        }
        
        else if (currentRaiseState == RaiseState.IsRaisedAgain)
        {
            raiseTimer += Time.deltaTime;
                if(raiseTimer>=extendedRaiseCardDuration)
            {
                currentRaiseState = RaiseState.NotRaised;
                raiseTimer = 0.0f;
                 if(currentRaisePlayerId!=-1)
                {
                UpdateHandScene(currentRaisePlayerId,new List<int>());
                }
            } 
        }
    }
    

    
    // 实现在UI层显示普通出牌逻辑
    public void ShowChiToSelector(List<int> handCards, Action<int> callback)
    {
      // 为每张手牌添加点击事件
            foreach (var card in handCards)
            {
                // 获取手牌对象
                GameObject cardObj = playerHandCardObjects[card];
                // 获取按钮组件
                Button btnComponent = cardObj.GetComponent<Button>();
                
                // 配置点击事件
                btnComponent.onClick.AddListener(() =>
                {
                    callback(card);
                });
            }
    
        Console.WriteLine("此处的出牌界面已实现，暂时先用文字表示");
    }

    // 实现在UI层显示碰牌选项的逻辑
    public void ShowPengToSelector(List<List<int>> options, Action<List<int>> callback)
    {
         // 清理已有面板
    if (currentOperationPanel != null)
    {
        Destroy(currentOperationPanel);
    }
    
    // 实例化带自动布局的面板
    currentOperationPanel = Instantiate(operationPanelPrefab, canvas.transform);
    var layoutGroup = currentOperationPanel.AddComponent<HorizontalLayoutGroup>();
    layoutGroup.spacing = 10;
    layoutGroup.padding = new RectOffset(20, 20, 20, 20);

    // 动态创建选项按钮
    foreach (var option in options)
    {
        var currentOption = option; // 创建局部变量
        
        // 使用预制体创建按钮
        GameObject optionBtn = Instantiate(buttonPrefab, currentOperationPanel.transform);
        var btnComponent = optionBtn.GetComponent<Button>();
        
        // 设置按钮文本
        var btnText = optionBtn.GetComponentInChildren<Text>();
        btnText.text = "碰: " + string.Join(", ", currentOption);

        // 配置点击事件
        btnComponent.onClick.AddListener(() =>
        {
            callback(currentOption);
            Destroy(currentOperationPanel);
        });
    }
        Console.WriteLine("此处的碰牌界面已实现，暂时先用文字表示");
    }
    // 实现在UI层显示杠牌选项的逻辑 
    public void ShowGangToSelector(List<List<int>> options, Action<List<int>> callback)
    {
          // 清理已有面板
    if (currentOperationPanel != null)
    {
        Destroy(currentOperationPanel);
    }
    
    // 实例化带自动布局的面板
    currentOperationPanel = Instantiate(operationPanelPrefab, canvas.transform);
    var layoutGroup = currentOperationPanel.AddComponent<HorizontalLayoutGroup>();
    layoutGroup.spacing = 10;
    layoutGroup.padding = new RectOffset(20, 20, 20, 20);//左右上下边距

    // 动态创建选项按钮
    foreach (var option in options)
    {
        var currentOption = option; // 创建局部变量
        
        // 使用预制体创建按钮
        GameObject optionBtn = Instantiate(buttonPrefab, currentOperationPanel.transform);
        var btnComponent = optionBtn.GetComponent<Button>();
        
        // 设置按钮文本
        var btnText = optionBtn.GetComponentInChildren<Text>();
        btnText.text = "杠: " + string.Join(", ", currentOption);

        // 配置点击事件
        btnComponent.onClick.AddListener(() =>
        {
            callback(currentOption);
            Destroy(currentOperationPanel);
        });
    }
        Console.WriteLine("此处的杠牌界面已实现，暂时先用文字表示");
    }

    // 实现在UI层显示胡牌选项的逻辑
    public void ShowHuToSelector(List<List<int>> options, Action<List<int>> callback)
{
    // 清理已有面板
    if (currentOperationPanel != null)
    {
        Destroy(currentOperationPanel);
    }
    
    // 实例化带自动布局的面板
    currentOperationPanel = Instantiate(operationPanelPrefab, canvas.transform);
    var layoutGroup = currentOperationPanel.AddComponent<HorizontalLayoutGroup>();
    layoutGroup.spacing = 10;
    layoutGroup.padding = new RectOffset(20, 20, 20, 20);

    // 动态创建选项按钮
    foreach (var option in options)
    {
        var currentOption = option; // 创建局部变量
        
        // 使用预制体创建按钮
        GameObject optionBtn = Instantiate(buttonPrefab, currentOperationPanel.transform);
        var btnComponent = optionBtn.GetComponent<Button>();
        
        // 设置按钮文本
        var btnText = optionBtn.GetComponentInChildren<Text>();
        btnText.text = "胡: " + string.Join(", ", currentOption);

        // 配置点击事件
        btnComponent.onClick.AddListener(() =>
        {
            callback(currentOption);
            Destroy(currentOperationPanel);
        });
    }
}

    //实现弃牌界面更新
    public void UpdateDiscardScene(int playerId, List<int> discardCard)
    {
        //清空弃牌界面
        foreach(Transform child in discardCardArea)
        {
            Destroy(child.gameObject);
        }
       foreach (var card in discardCard)
       {
           GameObject cardObj = Instantiate(discardCardPrefab, discardCardArea);
           cardObj.GetComponent<CardUI>().Initialize(card);
           playerDiscardCardObjects[card] = cardObj;
       }
    }

        // 触发卡牌点击事件
        private void OnCardClicked(int card)
    {
        
        if (cardClickedCallback != null)
        {
            cardClickedCallback(card);
        }
    }



    // 设置卡牌点击回调
    public void SetCardClickedCallback(Action<int> callback)
    {
        cardClickedCallback = callback;
    }

    //清理手牌
    public void ClearHandCard(int playerId)
    {
        foreach (var cardObj in playerHandCardObjects.Values) // 改为遍历字典中的对象
        {
            Destroy(cardObj); // 销毁已存在的卡牌对象
        }
        playerHandCardObjects.Clear(); // 清空字典
    }

    
    //清理弃牌
    public void ClearDiscardCard(int playerId)
    {
        foreach (var cardObj in playerDiscardCardObjects.Values) // 改为遍历字典中的对象
        {
            Destroy(cardObj); // 销毁已存在的卡牌对象
        }
          playerDiscardCardObjects.Clear(); // 清空字典
    }
//     //显示冲突面板界面
//    public void ShowConflictOptions(List<string> options, Action<string> callback)
//    {
//        currentOperationPanel = Instantiate(operationPanelPrefab, canvas.transform);
//        foreach (var option in options)
//        {
//            GameObject optionBtn = new GameObject("OptionButton");
//            optionBtn.transform.SetParent(currentOperationPanel.transform);
//            Button btnComponent = optionBtn.AddComponent<Button>();
//            btnComponent.onClick.AddListener(() =>
//            {
//                callback(option);
//                Destroy(currentOperationPanel);
//            });
//        }
//    }
   public void ShowConflictOptions(List<string> options, Action<string> callback)
{
    // 清理已有面板
    if(currentOperationPanel != null) 
    {
        Destroy(currentOperationPanel);
    }
    
    // 实例化带自动布局的面板
    currentOperationPanel = Instantiate(operationPanelPrefab, canvas.transform);
    var layoutGroup = currentOperationPanel.AddComponent<HorizontalLayoutGroup>();
    layoutGroup.spacing = 10;
    layoutGroup.padding = new RectOffset(20, 20, 20, 20);

    // 动态创建选项按钮
    foreach (var option in options)
    {
        var currentOption = option; // 创建局部变量
        
        // 使用预制体创建按钮
        GameObject optionBtn = Instantiate(buttonPrefab, currentOperationPanel.transform);
        var btnComponent = optionBtn.GetComponent<Button>();
        
        // 设置按钮文本
        var btnText = optionBtn.GetComponentInChildren<Text>();
        btnText.text = currentOption;

        // 配置点击事件
        btnComponent.onClick.AddListener(() =>
        {
            callback(currentOption);
            Destroy(currentOperationPanel);
        });
    }
}

    //显示游戏结束界面
    public void ShowGameEndScene(int playerId, int winningCard)
    { 
        GameObject gameEndPanel = Instantiate(gameEndPanelPrefab, canvas.transform);
        GameObject winningCardObj = Instantiate(handCardPrefab, gameEndPanel.transform);
        GameObject conflictOptionsPanel = Instantiate(conflictOptionsPanelPrefab, canvas.transform);
        conflictOptionsPanel.name = "ConflictOptionsPanel";
       //实例化游戏结束面板
       gameEndPanel.name="GameEndPanel";
       /*显示玩家id和胡牌*/
    } 
}
}